<template>
  <div
    class="chart-box"
    style="width: 100%; height: 100%"
    :style="{ backgroundColor: widgetOptions.setup.backgroundColor }"
  >
    <audio v-if="!chartStatus" ref="audioEl" :autoplay="true" controls></audio>
    <ChartEmpty v-if="chartStatus" :chartStatus="chartStatus" />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { AlgengineApi } from '@/api/vmiot/algengine'
import ChartEmpty from '../../components/chartEmpty.vue'
import Hls from 'hls.js'

const props = defineProps({
  widgetOptions: {
    type: Object as PropType<Record<string, any>>,
    required: true
  },
  isPreview: {
    type: Boolean,
    default: false
  }
})

const audioEl = ref<HTMLAudioElement | null>(null)
const audioUrl = ref()
const chartStatus = ref<string>(
  props.isPreview && !props.widgetOptions.data.signal ? 'taskError' : ''
)

const signal = computed(() => props.widgetOptions.data.signal)

const getData = async () => {
  if (signal.value.signalAccessType.includes('HTTP')) {
    try {
      const res = await AlgengineApi.getSignalRealtime({
        signalAccessParams: signal.value.signalAccessParams
      })
      audioUrl.value = res.msgPack.value.hls
      playVideo()
    } catch (error) {
      chartStatus.value = 'error'
    }
  }
}

let hls
const playVideo = () => {
  if (Hls.isSupported() && audioEl.value) {
    hls = new Hls()
    hls.loadSource(audioUrl.value)
    hls.attachMedia(audioEl.value)
    hls.on(Hls.Events.MANIFEST_PARSED, () => {
      audioEl.value?.play()
    })
  } else if (audioEl.value?.canPlayType('application/vnd.apple.mpegurl')) {
    audioEl.value.src = audioUrl.value
    audioEl.value.play()
  }
}

const refreshData = () => {
  if (props.isPreview) {
    getData()
  } else {
    // audioUrl.value = audioFile
  }
}

onMounted(() => {
  refreshData()
})

onBeforeUnmount(() => {
  if (hls) {
    hls.destroy()
    hls = null
  }
})
</script>

<style scoped></style>
